package com.ztom.v2;

/**
 * @author ZhangTao
 */
public class Code31ReverseNodesInKGroup {

    public class ListNode {
        int val;
        ListNode next;

        ListNode() {
        }

        ListNode(int val) {
            this.val = val;
        }

        ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }

    public ListNode reverseKGroup(ListNode head, int k) {
        if (head == null) {
            return head;
        }

        ListNode dummy = new ListNode(-1, head);
        ListNode help = dummy;

        // 每次指向分组链表的头和尾
        ListNode newHead = head;
        ListNode tail = dummy;

        while (newHead != null) {
            // 先走 k 得到当前分组
            for (int i = 0; i < k; i++) {
                tail = tail.next;
                // 不足直接返回, 所以不能边走边翻转
                if (tail == null) {
                    return dummy.next;
                }
            }

            // 记下一组的 head 用于重新链接链表
            ListNode next = tail.next;

            // 翻转分组链表
            ListNode[] nodes = reverse(newHead, tail);
            newHead = nodes[0];
            tail = nodes[1];

            // 链接
            tail.next = next;

            // 记录数据
            help.next = newHead;

            // 准备下一分组
            help = tail;
            newHead = next;
        }
        return dummy.next;
    }

    public ListNode[] reverse(ListNode h, ListNode t) {
        ListNode pre = null;
        ListNode cur = h;
        while (pre != t) {
            ListNode next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return new ListNode[]{t, h};
    }
}
